﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Windows.Admin.Domain;
using Windows.Admin.Infrastructure.EFCore;
using Windows.Infrastructure.Share.CustomException;
using Windows.Infrastructure.Share.Security;
using Windows.Infrastructure.EFCore.Share.Extensions;
using Microsoft.IdentityModel.Tokens;
using Windows.Infrastructure.Share.Extensions;
using System;
using Windows.Admin.Infrastructure.EFCore.Extensions;
using System.Security.Cryptography;
using System.Linq;

namespace Windows.Admin.Service
{
    public class AppService : IAppService
    {
        private readonly IMapper _mapper;
        private readonly AdminDbContext _db;
        private readonly ICurrentUser _currentUser;
        public AppService(IMapper mapper, AdminDbContext db, ICurrentUser currentUser)
        {
            _mapper = mapper;
            _db = db;
            _currentUser = currentUser;
        }
        /// <summary>
        /// 获取应用列表基础数据
        /// </summary>
        /// <param name="types"></param>
        /// <returns></returns>
        public async Task<List<AppResponse>> GetBasicApps(params int[] types)
        {
            List<App> apps = await _db.App.GetBasicApps(types).ToListAsync();
            return _mapper.Map<List<AppResponse>>(apps);
        }
        /// <summary>
        /// 获取级别应用列表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public async Task<List<AppResponse>> GetLevelApps(long id)
        {
            var model = await _db.App.FindByIdAsync(id) ?? throw new ApiException("应用不存在!");
            List<long> ids = new();
            if (!model.Level.IsNullOrEmpty())
            {
                model.Level!.Split(',').ToList().ForEach(x => ids.Add(x.ToLong()));
            }
            var list = await _db.App.Where(x => ids.Contains(x.Id)).ToListAsync();
            list = list.OrderBy(x => Array.IndexOf(ids.ToArray(), x.Id)).ToList();
            list.Add(model);
            return _mapper.Map<List<AppResponse>>(list);
        }
        /// <summary>
        /// 获取当前用户的桌面快捷方式列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<AppResponse>> GetCurrentUserShortuts()
        {
            var apps = await _db.Shortcut.Include(x => x.App).Where(x => x.UserId == _currentUser.Id).Select(s => s.App).ToListAsync();
            var appDtos = _mapper.Map<List<AppResponse>>(apps);
            return appDtos;
        }
        /// <summary>
        /// 获取显示在角落的应用列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<AppResponse>> GetCornerApps()
        {
            List<App> apps = await _db.App.Where(x => x.ShowCorner).ToListAsync();
            var appDtos = _mapper.Map<List<AppResponse>>(apps);
            return appDtos;
        }
        /// <summary>
        /// 应用管理窗体
        /// </summary>
        /// <returns></returns>
        public async Task<List<AppResponse>> Query()
        {
            List<App> apps = await _db.App.ToListAsync();
            return _mapper.Map<List<AppResponse>>(apps);
        }
        /// <summary>
        /// 获取id的应用详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AppResponse> Detail(int id)
        {
            var model = await _db.App.FindByIdAsync(id);
            return _mapper.Map<AppResponse>(model);
        }
        /// <summary>
        /// 应用保存
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task Save(AppSaveRequest request)
        {
            if (await _db.App.AnyAsync(x => x.Name.ToLower() == request.Name && x.Id != request.Id  && x.Type!=AppTypeEnum.Resource.ToInt()))
                throw new ApiException("应用名称已存在!");
            App? model = _mapper.Map<App>(request);
            if(request.Id != null)
            {
                model = await _db.App.FindByIdAsync(request.Id.Value) ?? throw new ApiException("应用不存在!");
                model.PId = request.PId;
                model.Type = request.Type;
                model.Name = request.Name;
                model.Component = request.Component;
                model.License = request.License;
                model.Icon = request.Icon;
                model.ShowCorner = request.ShowCorner;
                model.IsCustom = request.IsCustom;
                model.Width = request.Width;
                model.Height = request.Height;
                model.Sort = request.Sort;
                model.Remark = request.Remark;
            }
            if (request.Type == AppTypeEnum.Catalog.ToInt())
            {
                model.Component = "Catalog";
            }
            if (request.PId != null)
            {
                App? parent = await _db.App.FindByIdAsync(request.PId.Value);
                if (parent != null)
                {
                    if (parent.Level.IsNullOrEmpty())
                        model.Level = parent.Id + "";
                    else
                        model.Level = parent.Level + "," + parent.Id;
                }
            }
            if (request.Id == null)
                await _db.App.AddAsync(model);
            await _db.SaveChangesAsync();
        }
        /// <summary>
        /// 应用删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task Remove(long id)
        {
            var model = await _db.App.FindByIdAsync(id) ?? throw new ApiException("应用不存在!");
            var list = await _db.App.Where(x => x.Level != null && ("," + x.Level + ",").Contains("," + id + ",")).ToListAsync();
            if (list.Count > 0)
            {
                foreach (var l in list)
                {
                    l.IsEnable = false;
                }
            }
            model.IsEnable = false;
            await _db.SaveChangesAsync();
        }
    }
}
